package x.ovo.wechat.bot.contact;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import x.ovo.wechat.bot.common.contact.RetrievalStratrgy;
import x.ovo.wechat.bot.common.contact.RetrievalType;
import x.ovo.wechat.bot.common.entity.Contact;
import x.ovo.wechat.bot.common.http.WechatApi;

import java.time.Duration;
import java.util.Iterator;

/**
 * 根据备注获取联系人策略
 *
 * @author ovo, created by 2024/04/22
 */
public class RemarkStrategy extends RetrievalStratrgy {

    private final WechatApi api;
    private final TimedCache<String, Contact> cache = CacheUtil.newTimedCache(Duration.ofMinutes(10).toMillis());

    public RemarkStrategy(WechatApi api, Iterator<Contact> iterator) {
        this.api = api;
        this.cache.schedulePrune(Duration.ofMinutes(5).toMillis());
        while (iterator.hasNext()) {
            Contact account = iterator.next();
            this.cache.put(account.getRemarkName(), account);
        }
    }

    @Override
    public Contact getContact(Iterator<Contact> iterator, String key) {
        return this.cache.get(key, () -> {
            while (iterator.hasNext()) {
                Contact account = iterator.next();
                if (account.getRemarkName().equals(key)) {
                    return account;
                }
            }
//            return this.api.getContactByName(key);
            return null;
        });
    }

    @Override
    public void removeContact(String key) {
        this.cache.remove(key);
    }

    @Override
    public RetrievalType getType() {
        return RetrievalType.REMARK_NAME;
    }
}
